package com.example.test.handler;

import com.example.test.common.excetion.BusinessException;
import com.example.test.common.response.Response;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.xml.ws.EndpointReference;
import java.util.List;

/**
 * @author gyg
 * @version 1.0
 * @date 2020/4/18 18:50
 * @Description: 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    public <T> Response<T> businessException(Exception e){
        Response<T> response = new Response<T>();
        response.setSuccess(false);
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            response.setCode(businessException.getCode());
            response.setMessage(businessException.getMessage());
            return response;
        } /*else if(e instanceof BindException) {
            BindException bindException = (BindException)e;
            List<ObjectError> allErrors = bindException.getAllErrors();
            StringBuilder sb = new StringBuilder();
            allErrors.forEach(err -> sb.append(err.getDefaultMessage()).append(";"));
            response.setCode("400301");
            response.setMessage(sb.toString());
            return response;
        } */else if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException)e;
            List<ObjectError> allErrors = validException.getBindingResult().getAllErrors();
            StringBuilder sb = new StringBuilder();
            allErrors.forEach(err -> sb.append(err.getDefaultMessage()).append(";"));
            response.setCode("400301");
            response.setMessage(sb.toString());
            return response;
        }
        return Response.fail();
    }


}
